//
//  ProjectStatusModifyViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/29.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "ProjectStatusModifyViewController.h"
#import "EditorTableViewCell.h"
#import "Project_Step1ViewController.h"
#import <MBProgressHUD.h>
#import "ProjectManager.h"
#import <TPKeyboardAvoidingTableView.h>
#import <CustomIOSAlertView.h>

@interface ProjectStatusModifyViewController () {
    int projectStatus; // 1:进行中 4:未完成 2:已完成
    MBProgressHUD *HUD;
    BOOL priceModified;
}

@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableView;
@property (nonatomic,assign) double actuallyPrice;
@property (nonatomic,retain) UITextField *priceTextField;

@end

@implementation ProjectStatusModifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    [self loadData];
}

/**
 *  初始化数据
 */
- (void)initData {
    projectStatus = 1; //默认是进行中的项目
    self.actuallyPrice = 0;
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    projectStatus = self.projectData.phase;
    [self.tableView reloadData];
}

#pragma mark - 初始化视图
- (void)setupViews{
    
    UIView *actionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, kNavigation_Bar_Height)];
    
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareBtn setTitle:@"删除" forState:UIControlStateNormal];
    [shareBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    shareBtn.titleLabel.font = [UIFont systemFontOfSize: kListTitleFontSize];
    shareBtn.frame = CGRectMake(0, 0, 2*kListTitleFontSize, kListTitleFontSize);
    [shareBtn addTarget:self action:@selector(deleteButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    [actionView addSubview:shareBtn];
    shareBtn.centerY = kNavigation_Bar_Height/2;
    
    actionView.width = CGRectGetMaxX(shareBtn.frame);
    
    //自定义按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithCustomView:actionView];
    self.navigationItem.rightBarButtonItem = backBtn;
    
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    footerView.backgroundColor = [UIColor grayColor];
    [self.view addSubview: footerView];
    
    UIButton *viewBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width/2, KAction_Bar_Height)];
    [viewBtn setTitle:@"提交项目进度" forState:UIControlStateNormal];
    [viewBtn setBackgroundColor:CM_BOTTOM_LEFT_ACTION_BG_COLOR];
    viewBtn.titleLabel.font = [UIFont systemFontOfSize:kNavTitleFontSize];
    [viewBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [viewBtn addTarget:self action:@selector(submitProject) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:viewBtn];
    
    UIButton *viewBtn1 = [[UIButton alloc]initWithFrame:CGRectMake(kScreen_Width/2, 0, kScreen_Width/2, KAction_Bar_Height)];
    [viewBtn1 setTitle:@"修改项目信息" forState:UIControlStateNormal];
    [viewBtn1 setBackgroundColor:CM_BOTTOM_RIGHT_ACTION_BG_COLOR];
    viewBtn1.titleLabel.font = [UIFont systemFontOfSize:kNavTitleFontSize];
    [viewBtn1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [viewBtn1 addTarget:self action:@selector(modifyProjectInfo) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:viewBtn1];
    
    
    self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, self.view.height - kNavigation_Bar_Height - kStatus_Bar_Height - KAction_Bar_Height) style:UITableViewStylePlain];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
}

#pragma mark - 事件响应

- (void)deleteButtonClicked {
    [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"确定删除此项目？" cancelButtonTitle:@"确认" otherButtonTitles:[NSArray arrayWithObjects:@"取消", nil] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
        }
        else {
            
        }
    }];
}

- (void)submitProject {
    if (projectStatus == 2 && self.actuallyPrice <=0) {
        [Tools showMessageCenter:@"您还没有填写项目的成交价格！"];
        return;
    }
    if (projectStatus == 1) {
        [Tools showMessageCenter:@"请选择项目状态！"];
        return;
    }
    [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"提交项目进度后，项目不再允许修改，请确认！" cancelButtonTitle:@"确认" otherButtonTitles:[NSArray arrayWithObjects:@"取消", nil] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [self modifyProjectPhase:projectStatus price:self.actuallyPrice];
        }
        else {
            
        }
    }];
}

- (void)modifyProjectPrice:(double)price {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSDictionary *project = [self.projectData keyValues];
    
    [project setValue:[NSNumber numberWithInt:1] forKey:@"phase"];
    [project setValue:[NSNumber numberWithDouble:price] forKey:@"transPrice"];
    
    [params setObject:project forKey:@"prjInfo"];
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"项目成交价格更改中...";
    
    NSData *jsonData = [params JSONString];
    NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"json data:%@",json);
    
    [HttpClient postWithUrl:HTTP_POST_PROJECT_INFO token:[[AccountManager manager] token] paramDic:params resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        [HUD setHidden:YES];
        kTipAlert(@"修改项目成交价格成功！");
        self.projectData.transPrice = price;
        [[ProjectManager manager]saveProject:self.projectData];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:2]] withRowAnimation:UITableViewRowAnimationAutomatic];
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        kTipAlert(@"修改失败，请重试！");
        CMLog(@"错误信息为：%@",error);
    }];
}

- (void)deleteProject:(NSString *)guidId {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:guidId forKey:@"pid"];
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"项目删除中...";
    
    [HttpClient deleteWithUrl:HTTP_DELETE_PROJECT token:[[AccountManager manager] token] paramDic:params resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        [HUD setHidden:YES];
        [UIAlertView bk_showAlertViewWithTitle:@"提示" message:@"删除项目成功！" cancelButtonTitle:@"确认" otherButtonTitles:nil handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                [self.navigationController popViewControllerAnimated:YES];
            }
            else {
                
            }
        }];
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        kTipAlert(@"修改失败，请重试！");
        CMLog(@"错误信息为：%@",error);
    }];
}

- (void)modifyProjectPhase:(int)phase price:(double)price {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSDictionary *project = [self.projectData keyValues];
    
    [project setValue:[NSNumber numberWithInt:phase] forKey:@"phase"];
    [project setValue:[NSNumber numberWithDouble:price] forKey:@"transPrice"];
    
    [params setObject:project forKey:@"prjInfo"];
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"项目状态更改中...";
    
    NSData *jsonData = [params JSONString];
    NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"json data:%@",json);
    
    [HttpClient postWithUrl:HTTP_POST_PROJECT_INFO token:[[AccountManager manager] token] paramDic:params resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        [HUD setHidden:YES];
        kTipAlert(@"提交项目进度成功！");
        self.projectData.phase = phase;
        self.projectData.transPrice = price;
        projectStatus = phase;
        [[ProjectManager manager]saveProject:self.projectData];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        kTipAlert(@"修改失败，请重试！");
        CMLog(@"错误信息为：%@",error);
    }];
}


- (void)modifyProjectInfo {
    [[ProjectManager manager]saveProject:self.projectData];
    //修改项目信息，并且不再重新绑定项目模板
    [[ProjectManager manager]setProjectStatus:KPROJECT_STATUS_MODIFY];
    [[ProjectManager manager]bindProjectTemplate];
    
    Project_Step1ViewController *view = [Project_Step1ViewController new];
    [self.navigationController pushViewController:view animated:YES];
}

#pragma mark - 加载数据
/**
 *  加载视图所有的数据
 */
- (void)loadData {
    //[self loadNationData];
}

#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //项目进度
        static NSString *identifier3 = @"ProjectStatusCell";
        EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier3];
        if (cell == nil) {
            cell = [[EditorTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier3];
            //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        NSString *infoStr;
        if (projectStatus == 1) {
            infoStr = @"进行中";
        }
        else if (projectStatus == 4){
            infoStr = @"未成交";
        }
        else {
            infoStr = @"已成交";
        }
        [cell setTitleStr:@"项目进度" andColor:nil andHintStr:nil andInputViewIsHidden:YES andInfoStr:infoStr andUnit:nil];
        [cell setNavigationHint:@"请修改"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
    else if (indexPath.section == 1) {
        //总价
        static NSString *identifier3 = @"ProjectPriceCell";
        EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier3];
        if (cell == nil) {
            cell = [[EditorTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier3];
            //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        NSString *infoStr = [NSString stringWithFormat:@"%.2f", self.projectData.totalPrice];
        [cell setTitleStr:@"原价" andColor:nil andHintStr:nil andInputViewIsHidden:YES andInfoStr:infoStr andUnit:@"元"];
        [cell setNavigationHint:@" "];

        cell.accessoryType = UITableViewCellAccessoryNone;
        return cell;

    }
    else {
        //成交价
        static NSString *identifier3 = @"ProjectActuallyPriceCell";
        EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier3];
        if (cell == nil) {
            cell = [[EditorTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier3];
            //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        self.actuallyPrice = self.projectData.transPrice;
        NSString *infoStr = [NSString stringWithFormat:@"%.2f", self.projectData.transPrice];
        [cell setTitleStr:@"成交价" andColor:nil andHintStr:nil andInputViewIsHidden:YES andInfoStr:infoStr andUnit:@"元"];
        [cell setNavigationHint:@"请修改"];
        
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier3 = @"ProjectActuallyPriceCell";
    EditorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier3];
    if (cell == nil) {
        cell = [[EditorTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"ProjectActuallyPriceCell"];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return [cell getHeight];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        UIActionSheet *sheet = [UIActionSheet bk_actionSheetWithTitle:@"选择项目状态"];
        [sheet bk_addButtonWithTitle:@"进行中" handler:^{
            projectStatus = 1;
            [self.tableView reloadData];
        }];
        [sheet bk_addButtonWithTitle:@"未成交" handler:^{
            projectStatus = 4;
            [self.tableView reloadData];
        }];
        [sheet bk_addButtonWithTitle:@"已成交" handler:^{
            projectStatus = 2;
            [self.tableView reloadData];
        }];
        [sheet bk_setCancelButtonWithTitle:@"取消" handler:nil];
        [sheet showInView:self.view];
    }
    else if (indexPath.section == 1) {
        
    }
    else {
        [self editPrice:self.projectData.transPrice];
    }
}


-(void)editPrice:(double)price{
    CustomIOSAlertView *alert = [[CustomIOSAlertView alloc] init];
    [alert setUseMotionEffects:YES];
    
    UIView *subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width-50, 200)];
    
    //标题栏
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, subView.width, 50)];
    [titleView setUserInteractionEnabled:YES];
    
    titleView.backgroundColor = CM_ACTION_CELL_COLOR;
    [subView addSubview:titleView];
    //左上角、右上角圆角为7
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:titleView.bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(7, 7)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = titleView.bounds;
    maskLayer.path = maskPath.CGPath;
    titleView.layer.mask = maskLayer;
    
    //添加文字
    UILabel *titleLabel = [UILabel labelSingleLineFontSize:14 content:@"成交价"];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.centerY = titleView.centerY;
    titleLabel.centerX = titleView.centerX;
    [titleView addSubview:titleLabel];
    
    //此次报价
    UILabel *curLabel = [UILabel labelSingleLineFontSize:14 content:@"报价："];
    curLabel.x = 20;
    curLabel.y = CGRectGetMaxY(titleView.frame)+70;
    curLabel.textAlignment = NSTextAlignmentLeft;
    [subView addSubview:curLabel];
    
    self.priceTextField = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMaxX(curLabel.frame), curLabel.y, subView.width/2, curLabel.height)];
    self.priceTextField.textColor = CM_TABLE_DETAIL_COLOR;
    self.priceTextField.font = [UIFont systemFontOfSize:kListTitleFontSize];
    self.priceTextField.placeholder = [NSString stringWithFormat:@"%.2f元", price];
    
    self.priceTextField.keyboardType=UIKeyboardTypeDecimalPad;//设置键盘类型为数字的
    self.priceTextField.returnKeyType=UIReturnKeyDefault;//返回键的类型
    [self.priceTextField addTarget:self action:@selector(textFieldChange) forControlEvents:UIControlEventEditingChanged];
    [subView addSubview:self.priceTextField];
    //    [self.priceTextField addTarget:self action:@selector(textFieldChange) forControlEvents:UIControlEventEditingChanged];
    
    priceModified = NO;
    
    [alert setContainerView:subView];
    [alert setButtonTitles:@[@"确定", @"取消"]];
    [alert setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex) {
            case 1:
                
                break;
            case 0:
            {
                if (priceModified && self.priceTextField.text.length > 0) {
                    self.actuallyPrice = [self.priceTextField.text doubleValue];
                    [self modifyProjectPrice:self.actuallyPrice];
                }
            }
                break;
            default:
                break;
        }
    }];
    
    [alert show];
    
}

- (void)textFieldChange {
    priceModified = YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
